package com.plugins.pluginlib.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;

import com.plugins.pluginlib.IBasePluginActivity;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 插件工具
 */
public class PluginUtils {
    private static final String TAG = "PluginUtils";

    /**
     * 获取插件信息
     * @param context
     * @param apkFilepath
     * @return
     */
    public static PackageInfo getPackageInfo(Context context, String apkFilepath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = null;
        try {
            pkgInfo = pm.getPackageArchiveInfo(apkFilepath, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES|PackageManager.GET_META_DATA);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pkgInfo;
    }

    /**
     * 获取app图标
     * @param context
     * @param apkFilepath
     * @return
     */
    public static Drawable getAppIcon(Context context, String apkFilepath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = getPackageInfo(context, apkFilepath);
        if (pkgInfo == null) {
            return null;
        }

        ApplicationInfo appInfo = pkgInfo.applicationInfo;
        if (Build.VERSION.SDK_INT >= 8) {
            appInfo.sourceDir = apkFilepath;
            appInfo.publicSourceDir = apkFilepath;
        }

        return pm.getApplicationIcon(appInfo);
    }

    /**
     *
     * @param context
     * @param apkFilepath
     * @return
     */
    public static CharSequence getAppLabel(Context context, String apkFilepath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = getPackageInfo(context, apkFilepath);
        if (pkgInfo == null) {
            return null;
        }

        ApplicationInfo appInfo = pkgInfo.applicationInfo;
        if (Build.VERSION.SDK_INT >= 8) {
            appInfo.sourceDir = apkFilepath;
            appInfo.publicSourceDir = apkFilepath;
        }

        return pm.getApplicationLabel(appInfo);
    }

    public static String getProxyViewAction(String className, ClassLoader classLoader) {
        int activityType = getActivityType(className, classLoader);
        return getProxyViewActionByActivityType(activityType);
    }

    public static String getProxyViewAction(Class<?> cls) {
        int activityType = getActivityType(cls);
        return getProxyViewActionByActivityType(activityType);
    }

    private static String getProxyViewActionByActivityType(int activityType) {
        String proxyViewAction = null;

        switch (activityType) {
            case IConstants.ACTIVITY_TYPE_NORMAL: {
                proxyViewAction = IConstants.PROXY_ACTIVITY_VIEW_ACTION;
                break;
            }
            case IConstants.ACTIVITY_TYPE_FRAGMENT: {
                proxyViewAction = IConstants.PROXY_FRAGMENT_ACTIVITY_VIEW_ACTION;
                break;
            }
            case IConstants.ACTIVITY_TYPE_ACTIONBAR:
            case IConstants.ACTIVITY_TYPE_UNKNOWN:
            default:
                break;
        }

        if (proxyViewAction == null) {
            Log.e(TAG, "unsupported activityType:" + activityType);
        }

        return proxyViewAction;
    }

    private static int getActivityType(String className, ClassLoader classLoader) {
        int activityType = IConstants.ACTIVITY_TYPE_UNKNOWN;

        try {
            Class<?> cls = Class.forName(className, false, classLoader);
            activityType = getActivityType(cls);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return activityType;
    }

    private static int getActivityType(Class<?> cls) {
        int activityType = IConstants.ACTIVITY_TYPE_UNKNOWN;

        try {
            if (cls.asSubclass(IBasePluginActivity.class) != null) {
                activityType = IConstants.ACTIVITY_TYPE_NORMAL;
                return activityType;
            }
        } catch (ClassCastException e) {
            // ignored
        }

        // TODO: handle other activity types, ActionbarActivity,eg.
        return activityType;
    }

    public static void showDialog(Activity activity, String title, String message) {
        new AlertDialog.Builder(activity).setTitle(title).setMessage(message)
                .setPositiveButton("确定", null).show();
    }

    public static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从assets拷贝到file
     * @param context
     * @param saveFile
     */
    public static void copyFilesFromAssets(Context context, String fromPath, String saveFile,boolean isAssets){
        try {
            Log.e("copyFilesFromAssets","fromPath="+fromPath+",saveFile="+saveFile);
            InputStream is = isAssets?context.getAssets().open(fromPath):new FileInputStream(fromPath);;
            FileOutputStream fos = new FileOutputStream(new File(saveFile));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                // buffer字节
                fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
            }
            fos.flush();// 刷新缓冲区
            is.close();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("copyFilesFromAssets",e.getMessage());
        }
    }
}
